//
//  HMStatusesViewModel.m
//  SinaWeiBo
//
//  Created by WGP on 16/4/13.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "HMStatusesViewModel.h"
#import "HMUserAccountViewModel.h"
#import "HMUserAccount.h"
#import "HMStatuses.h"
#import <SDWebImageManager.h>

@interface HMStatusesViewModel ()

@property(nonatomic,assign)BOOL isLoadingStatus;

@end

@implementation HMStatusesViewModel

+(instancetype)sharedInstance
{
    static HMStatusesViewModel *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        instance = [[self alloc] init];
    });
    return instance;
}


-(void)loadUserDataWithSince_id:(int64_t)since_id max_id:(int64_t)max_id finished:(void(^)(NSArray *statuses, NSError *error))finishedBlock
{
    if (self.isLoadingStatus)
    {
        HMLog(@"已经有加载任务了");
        NSError *error = [[HMNetWorkTool sharedNetWorkTool] errorWith:HMNetWorkErrorOfRepeateLoadStatus];
        finishedBlock(nil,error);
        return ;
    }
    
    self.isLoadingStatus = YES;
    
//    1.url
    NSString *urlStr = @"https://api.weibo.com/2/statuses/home_timeline.json";
    
//    2.参数
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    parameters[@"access_token"] = [HMUserAccountViewModel sharedInstance].userAccount.access_token;

    
    if (since_id > 0)
    {
        parameters[@"since_id"] = @(since_id);
        
    }else if(max_id > 0)
    {
        parameters[@"max_id"] = @(max_id);
    }
    
//    3.get请求
    [[HMNetWorkTool sharedNetWorkTool] GET:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        self.isLoadingStatus = NO;
        
        NSDictionary *result = (NSDictionary *)responseObject;

        NSArray *statuses = result[@"statuses"];
        
        NSMutableArray *statusesM = [NSMutableArray array];
        
        for (NSDictionary *dict in statuses) {
            HMStatuses *status = [HMStatuses statusWithDict:dict];
            [statusesM addObject:status];
        }
        
//        成功回调
        [self cacheWebImage:statusesM finished:finishedBlock];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        self.isLoadingStatus = NO;
//        失败回调
        finishedBlock(nil,error);
        
    }];
    
}

-(void)cacheWebImage:(NSArray *)statuses finished:(void(^)(NSArray *statuses, NSError *error))finishedBlock
{
    dispatch_group_t group = dispatch_group_create();
    
    for (HMStatuses *status in statuses) {
        
        NSArray *downloadURLs = status.pic_urlsArr;
        
        if (downloadURLs == nil) {
            
            downloadURLs = status.retweeted_status.pic_urlsArr;
            
        }
        
        if (downloadURLs.count == 1) {
            
            NSURL *url = [downloadURLs firstObject];
            dispatch_group_enter(group);
            
            [[SDWebImageManager sharedManager] downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                
//                异步下载回调
                dispatch_group_leave(group);
                
                if (error != nil)
                {
                    HMLog(@"下载图片失败!");
                    return ;
                }
            }];
        }
    }
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
       
//        HMLog(@"SD下载所有图片完成!");
//        下载后去控制器刷新tableView
        finishedBlock(statuses,nil);
    });
}


@end







